import React, { Component } from 'react';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Divider,
  Drawer,
  Form,
  Input,
  Popconfirm,
  Radio,
  Row,
  Select,
  Tabs,
  Tree,
  Upload,
} from 'antd';
import styled from 'styled-components';
import BaseComponent from '@/components/BaseComponent';
import iconAgreement from '@/assets/icon_agreement.png';
import { defDrawerWidth, bmxyImgPrefixUrl, njzdImgPrefixUrl } from '@/defaultSettings';
import { DivFooter, LFlexHDiv } from '@/components/MHtmlTag';

import {
  FormItem4Input,
  FormItem4Select,
  FormItem4Radio,
  FormItem5Select,
  FormItem4TreeSelect,
  FormItem4InputPwd,
} from '../MCols';
import styles from './index.less';

const { TabPane } = Tabs;
const ThumbnailBox = styled.div`
  width: 103px;
  height: 103px;
  display: flex;
  align-items: center;
  margin-top: 8px;

  .thumbnailImage {
    width: 103px;
    height: 103px;
  }

  .delBtn {
    margin-left: 16px;
  }
`;

/**
 * 编辑页面
 */

class AddOrEditView extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: '1',
      ndaUrl: '',
      ndaPath: '',

      // 是否正在上传
      isUploading: false,
      xbData: [
        {
          dictName: '男',
          dictValue: 1,
        },
        {
          dictName: '女',
          dictValue: 2,
        },
      ],
      statusData: [
        {
          dictName: '正常',
          dictValue: 1,
        },
        {
          dictName: '禁用',
          dictValue: 0,
        },
      ],
      record: {},
    };
  }

  componentDidMount() {
    const { record, isAddOrEdit } = this.props;
    this.setState({
      record,
      ndaUrl: record.ndaUrl,
    });
    // // 新增时,用户状态默认设置为1:启用
    // if (isAddOrEdit) {
    //   const { form } = this.props;
    //   debugger;
    //   form.setFieldsValue({ status: 1 });
    // }
  }

  render() {
    let { onClose, record, form, roleData, orgData, visible, isAddOrEdit, title } = this.props;

    const { getFieldDecorator } = form;
    if (isAddOrEdit == true) {
      record = {};
    }
    // 从state中获取参数
    const { activeKey, ...otherProps } = this.state;
    const disabled = false;
    return (
      <Drawer
        title={title}
        placement="right"
        width={defDrawerWidth}
        closable
        onClose={e => {
          if (onClose) {
            onClose(e);
          }
        }}
        visible={visible}
        className={styles.editableTable}
      >
        <Tabs defaultActiveKey={activeKey} onChange={this.handleTabChange}>
          <TabPane tab="基本信息" key="1" />
          <TabPane tab="账号信息" key="2" />
        </Tabs>

        <Card bordered>
          {/* 基本信息 */}
          <Form>
            <Row gutter={16} style={{ display: activeKey == 1 ? 'block' : 'none' }}>
              <FormItem4TreeSelect
                form={form}
                label="机构名称"
                fieldName="orgId"
                required
                items={orgData}
                initialValue={record ? record.orgId : ''}
              />
              <FormItem4Input
                form={form}
                label="所属部门"
                fieldName="departmentName"
                required={true}
                initialValue={record ? record.departmentName : ''}
              />
              <FormItem4Input
                form={form}
                label="专业"
                fieldName="profession"
                required={false}
                initialValue={record ? record.profession : ''}
              />
              <FormItem4Input
                form={form}
                label="职务"
                fieldName="job"
                required={false}
                initialValue={record ? record.job : ''}
              />
              <FormItem4Input
                form={form}
                label="职称"
                fieldName="jobTitle"
                required={false}
                initialValue={record ? record.jobTitle : ''}
              />
              <FormItem4Input
                form={form}
                label="姓名"
                fieldName="nickname"
                required
                initialValue={record ? record.nickname : ''}
              />
              <FormItem4Select
                form={form}
                label="性别"
                fieldName="gender"
                required={false}
                items={this.state.xbData}
                initialValue={record ? record.gender : ''}
              />
              <FormItem4Input
                form={form}
                label="联系电话"
                fieldName="mobile"
                required
                initialValue={record ? record.mobile : ''}
              />
              <FormItem4Input
                form={form}
                label="邮箱"
                fieldName="email"
                required={true}
                initialValue={record ? record.email : ''}
              />
              <FormItem4Input
                form={form}
                label="邮政编码"
                fieldName="postalCode"
                required={false}
                initialValue={record ? record.postalCode : ''}
              />
              <FormItem4Input
                form={form}
                label="邮寄地址"
                fieldName="postalAddress"
                required={false}
                initialValue={record ? record.postalAddress : ''}
              />
            </Row>
            <Row style={{ display: activeKey == 1 ? 'block' : 'none', marginBottom: '16px' }}>
              <Col className="gutter-row" span={12}>
                <Form.Item label="保密协议" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                  {this.state.ndaUrl && this.state.ndaUrl != '' ? (
                    <div className={styles.agreementImageBox}>
                      <img
                        src={iconAgreement}
                        className={styles.agreementImage}
                        onClick={() => {
                          const url = `${bmxyImgPrefixUrl}${this.state.ndaUrl}`;
                          window.open(url);
                        }}
                      />
                    </div>
                  ) : (
                    <Upload
                      listType="picture-card"
                      className={styles.agreementImage}
                      showUploadList={false}
                      action="/api/file/file/uploadFile4Report"
                      beforeUpload={this.handleUploadBefore}
                      onChange={info => {
                        this.handleUploadChange({ info });
                      }}
                    >
                      上传
                    </Upload>
                  )}
                  {this.state.ndaUrl && this.state.ndaUrl != '' ? (
                    <div>
                      {disabled ? null : (
                        <>
                          <Button
                            type="primary"
                            size="small"
                            style={{ marginTop: '6px' }}
                            className={styles.previewBtn}
                            onClick={() => {
                              window.open(`${bmxyImgPrefixUrl}${this.state.ndaUrl}`);
                            }}
                          >
                            预览
                          </Button>
                          <Popconfirm
                            title="确定删除吗?"
                            onConfirm={() => {
                              if (this.handleDelImage) {
                                this.handleDelImage();
                              }
                            }}
                          >
                            <Button type="danger" size="small" style={{ marginLeft: '4px' }}>
                              删除
                            </Button>
                          </Popconfirm>
                        </>
                      )}
                    </div>
                  ) : (
                    <div />
                  )}
                </Form.Item>
              </Col>
            </Row>
            {/* 账号信息 */}
            <Row gutter={16} style={{ display: activeKey == 2 ? 'block' : 'none' }}>
              <FormItem4Input
                form={form}
                label="登陆账号"
                fieldName="username"
                required
                initialValue={record ? record.username : ''}
              />
              <Col className="gutter-row" span={12}>
                <Form.Item
                  label="登录密码"
                  required
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 16 }}
                >
                  {getFieldDecorator('password', {
                    rules: [
                      {
                        required: true,
                        message: '请输入密码',
                      },
                      {
                        validator: this.validatePassword,
                      },
                    ],
                  })(<Input.Password autoComplete="off" placeholder={'请输入'} />)}
                </Form.Item>
              </Col>

              {/* <FormItem4InputPwd
              form={form}
              label="登录密码"
              fieldName="password"
              required
           
             
              initialValue={record ? record.password : 'Wny@2023'}
            // getFieldDecorator={function (password) {
          
            // }}
            /> */}
              <FormItem5Select
                form={form}
                label="请选择权限"
                fieldName="roleId"
                required
                items={roleData}
                initialValue={record ? record.partId : ''}
              />
              <FormItem4Radio
                form={form}
                label="状态"
                fieldName="status"
                required
                items={this.state.statusData}
                // initialValue={isAddOrEdit ? 1 : record ? record['status'] : ''}
                initialValue={record ? record.status : ''}
              />
            </Row>
          </Form>
        </Card>

        <DivFooter>
          <LFlexHDiv>
            {isAddOrEdit !== false && (
              <LFlexHDiv flex="1" justifyContent="center">
                <Button
                  style={{
                    marginRight: 8,
                    width: '120px',
                  }}
                  onClick={() => {
                    if (onClose) {
                      onClose();
                    }
                  }}
                  // loading={this.props.isPosting}
                >
                  取消
                </Button>

                <Popconfirm
                  title="确认执行当前操作吗?"
                  onConfirm={this.handleSubmit}
                  okText="是"
                  cancelText="否"
                >
                  <Button
                    style={{
                      marginRight: 8,
                      width: '120px',
                    }}
                    type="primary"
                    // loading={this.props.isPosting}
                  >
                    提交
                  </Button>
                </Popconfirm>
              </LFlexHDiv>
            )}

            {isAddOrEdit === false && (
              <LFlexHDiv flex="1" justifyContent="center">
                <Button
                  style={{
                    marginRight: 8,
                    width: '120px',
                  }}
                  onClick={() => {
                    if (onClose) {
                      onClose();
                    }
                  }}
                  // loading={this.props.isPosting}
                >
                  取消
                </Button>

                <Popconfirm
                  title="确认执行当前操作吗?"
                  onConfirm={this.handleEdit}
                  okText="是"
                  cancelText="否"
                >
                  <Button
                    style={{
                      marginRight: 8,
                      width: '120px',
                    }}
                    type="primary"
                    // loading={this.props.isPosting}
                  >
                    保存
                  </Button>
                </Popconfirm>
              </LFlexHDiv>
            )}
          </LFlexHDiv>
        </DivFooter>
      </Drawer>
    );
  }

  validatePassword = (rule, value, callback) => {
    const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[a-zA-Z\d\W_]{8,}$/;
    if (!value) {
      return;
    }
    if (!reg.test(value)) {
      callback('密码必须8位以上,包含大小写字母,数字特殊符号');
    }
  };

  /**
   * 执行提交
   */
  handleSubmit = () => {
    const { form, onSubmit } = this.props;
    // 表单数据
    const fieldsValue = form.getFieldsValue();
    if (onSubmit) {
      onSubmit(fieldsValue);
    }
  };

  handleDelImage = () => {
    this.setState({
      ndaUrl: '',
      ndaPath: '',
    });
  };

  handleUploadBefore = (file, fileList) => {
    this.setState({ isUploading: true }, () => {
      this.hide = this.loadingMessage('正在上传...');
    });
    return true;
  };

  handleUploadChange = ({ info }) => {
    if (info.file.status !== 'uploading') {
      this.setState(
        {
          fileList: info.fileList,
        },
        () => {}
      );
    }
    if (info.file.status === 'done') {
      const { response } = info.file;
      const {
        data: { filePath, originalFilename },
      } = response;
      const arr = filePath.split('/');
      // 文件前缀
      const prefix = arr[arr.length - 2];
      const url = `${prefix}/${originalFilename}`;
      this.setState({
        ndaUrl: url,
        ndaPath: filePath,
        isUploading: false,
      });
      if (this.hide) {
        this.hide();
      }
      this.successMessage('上传成功');
    } else if (info.file.status === 'error') {
      this.errorMessage('文件上传出错,请联系管理员');
    }
  };

  /** 执行编辑 */
  handleEdit = () => {
    const { form, onEdit } = this.props;
    const fieldsValue = form.getFieldsValue();
    const {
      ndaUrl,
      record: { id },
    } = this.state;
    const data = { ...fieldsValue, ndaUrl, id };
    if (!fieldsValue.password) {
      this.errorMessage('请设置登录密码');
      return;
    } else {
      const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[a-zA-Z\d\W_]{8,}$/;
      if (!reg.test(fieldsValue.password)) {
        this.errorMessage('密码必须8位以上,包含大小写字母,数字特殊符号');

        return;
      }
      if (onEdit) {
        onEdit(data);
      }
    }

    // form.validateFields(fieldsValue, { focus: false }, (err, values) => {

    //   if (!err) {
    //     if (onEdit) {
    //       onEdit(data);
    //     }
    //   }
    // });
  };

  handleTabChange = key => {
    this.setState({ activeKey: key });
  };
}

export default Form.create()(AddOrEditView);
